package com.sf.wisdomkg.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.sf.wisdomkg.R;
import com.sf.wisdomkg.utils.CommonUtils;
import com.sf.wisdomkg.utils.LoadingDialog;
import com.sf.wisdomkg.utils.Sha1;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Date;

/**
 * Created by Administrator on 2017/9/22.
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String SHARE_CONTENT = "app_";
    private SharedPreferences setting;

    private Button loginBtn;
    private EditText login_name,password_ed;

    private String baseUrl = CommonUtils.IP_S;

    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initView();
        if (!setting.getString("phone","").equals("")){
            login_name.setText(setting.getString("phone",""));
        }
        loginBtn.setOnClickListener(this);
//        getToken("15822362523","");
//        8O+yooF+BLyMTLVblBJtl4T3aWtrDW2rcSAS4FWSTNgALXoHdnAPN9FgFbyJys8bCLAam9i8f9TjvNSvSJP/pRk9YS2V84Cp
    }

    /**
     * 初始化
     */
    private void initView() {
        loginBtn = (Button) findViewById(R.id.loginBtn);
        login_name = (EditText)findViewById(R.id.login_name);
        password_ed = (EditText)findViewById(R.id.password_ed);

        setting = this.getSharedPreferences(SHARE_CONTENT,0);
        loadingDialog = new LoadingDialog(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loginBtn:
                Login();
                break;
        }
    }

    /**
     * 获取融云的token
     */
    private void getToken(String uid, String userName) {
        String newUserName = "智慧会员";
        if (!userName.equals("")) {
            newUserName = userName;
        }
        // 登录成功获取token值
        Date dt = new Date();
        Long time = dt.getTime();
        String Signature = "3Nn2AXaWY7BvME" + "14314" + time.toString();
        Sha1 sh = new Sha1();
        String token_url = "http://api.cn.ronghub.com/user/getToken.json";
        RequestParams params = new RequestParams(token_url);
        //参数设置
        params.addParameter("userId", uid);
        params.addParameter("name", newUserName);
        params.addParameter("portraitUri", "http://101.201.36.239:8083/job/header.png");
        params.addHeader("RC-App-Key", "6tnym1br6cqu7");
        params.addHeader("RC-Nonce", "14314");
        params.addHeader("RC-Timestamp", time.toString());
        params.addHeader("RC-Signature", sh.encryptToSHA(Signature));
        params.addHeader("Content-Type", "application/x-www-form-urlencoded");
        //联网设置
        params.setCacheMaxAge(1000 * 60);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("返回的值" + result);
                //解析result
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        SharedPreferences.Editor editor = setting.edit();
                        editor.putString("token",jsonObject.optString("token"));
                        editor.apply();
                        Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                        startActivity(intent);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                Toast.makeText(LoginActivity.this, "连接服务器失败,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(LoginActivity.this, "请求超时,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }


    /**
     * 登录接口
     */
    private void Login() {
        final String username = login_name.getText().toString();
        String password = password_ed.getText().toString();
        if (username.equals("")||password.equals("")){
            Toast.makeText(LoginActivity.this, "用户名或密码不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        loadingDialog.setMessage("登录中").show();
        RequestParams params = new RequestParams(baseUrl + "/kindergarten/app/login");
        params.addParameter("username",login_name.getText().toString());
        params.addParameter("password",password_ed.getText().toString());

        //联网设置
        params.setCacheMaxAge(1000 * 60);
        params.setConnectTimeout(9000);
        System.out.println("得到的结果"+params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("得到的结果"+result);
                //解析result
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.optString("status").equals("true")) {
                            try {
                                JSONObject jsonObj = new JSONObject(jsonObject.optString("data"));
                                SharedPreferences.Editor editor = setting.edit();
                                editor.putString("sessionId",jsonObj.optString("id"));
                                editor.putString("userName",jsonObj.optString("userName"));
                                editor.putString("roleId",jsonObj.optString("roleId"));
                                editor.putString("returnId",jsonObj.optString("returnId"));
                                editor.putString("teacherPhone",jsonObj.optString("teacherPhone"));
                                editor.putString("phone",username);
                                editor.putString("teacherName",jsonObj.optString("teacherName"));
                                editor.putString("kindPhone",jsonObj.optString("kindPhone"));
                                editor.apply();
                                if (jsonObj.optString("roleId").equals("1")){
                                    getToken(jsonObj.optString("kindPhone"),jsonObj.optString("userName"));
                                }else {
                                    getToken(jsonObj.optString("userName"),jsonObj.optString("userName"));
                                }


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }else{
                            Toast.makeText(LoginActivity.this, "用户名密码输入有误，请重新输入！", Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                System.out.println("报错"+ex);
                Toast.makeText(LoginActivity.this, "连接服务器失败,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(LoginActivity.this, "请求超时,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                loadingDialog.dismiss();
            }
        });
    }
}
